import { useState, useEffect } from "react";
import { message, Radio, Button, Select, DatePicker } from "antd";
import { PartitionOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import { observer } from "Mobx-react";
import type { questionType, optionType, answerType } from "@/types/index";
import { surveyStore } from "@/stores/survey";
import { typeEnum } from "@/assets/common/enums";
import { ScreenContent } from "../stye";

interface screenType {
  value: string;
  id: number;
  option: optionType[];
  answer: number[];
}

const { RangePicker } = DatePicker;
const { PAGING, PARAGRAPH, FILL, SLIDER, MATRIX_SLIDER } = typeEnum;
const noConcernItem = [PAGING, PARAGRAPH, FILL, SLIDER, MATRIX_SLIDER];
const dateFormat = "YYYY-MM-DD";

function Screen({ onScreenQuery }: { onScreenQuery: (date: string[], condition: string, answer: answerType[]) => void }) {
  const [screenShow, setScreenShow] = useState(false);
  const [conditionValue, setCondition] = useState("and");
  const [screenData, setScreenData] = useState<screenType[]>([]);
  const [screenQuestion, setScreenQuestion] = useState<questionType[]>([]);
  const [date, setDate] = useState<[Dayjs | null, Dayjs | null] | null>(null);

  useEffect(() => {
    const survey = surveyStore.surveySelected(surveyStore.surveyId);
    const questionList: questionType[] = [];
    if (survey) {
      for (const item of survey.question) {
        if (!noConcernItem.includes(item.type)) {
          if (item.children && item.children.length) {
            for (const child of item.children) {
              child.title = item.title + "-" + child.title;
              questionList.push(child);
            }
          } else {
            questionList.push(item);
          }
        }
      }
    }
    setScreenQuestion(questionList);
    setScreenData([]);
    setCondition("and");
    setScreenShow(false);
  }, [surveyStore.surveyId]);

  //增加条件
  const addCondition = () => {
    if (screenData.length == screenQuestion.length) return message.info("已超过可关联题目数量！");
    screenData.push({
      value: "",
      id: screenData.length + 1,
      option: [],
      answer: []
    });
    setScreenData([...screenData]);
  };

  // 删除条件
  const removeCondition = (index: number) => {
    screenData.splice(index, 1);
    setScreenData([...screenData]);
  };
  //选择题目
  const questionChange = (index: number, value: number) => {
    if (screenData[index].id === value) return;
    let ids = screenData.map((item: any) => item.id).indexOf(value);
    if (ids !== -1) {
      screenData[index].value = screenQuestion.find((item: any) => item.id == screenData[index].id)?.title || "";
      return message.info("关联题目不能重复");
    }
    let data = screenQuestion.find(item => item.id == value);
    screenData[index].value = data?.title || "";
    screenData[index].id = value;
    screenData[index].option = data?.option || [];
    setScreenData([...screenData]);
  };
  //重置
  const reset = () => {
    setDate(null);
    setScreenData([]);
    setCondition("and");
  };
  //查询
  const screenClick = () => {
    const dateInfo = ["", ""];
    const data = screenData.filter(item => item.answer.length > 0);
    setScreenData([...data]);
    const answer: answerType[] = data.map(item => ({ questionId: item.id, content: item.answer }));
    if (date && date[0] && date[1]) {
      const time = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").split(" ");
      const dateData = [date[0].format(dateFormat), date[1].format(dateFormat)];
      let end = "23:59:59";
      dateInfo[0] = dateData[0] + " 00:00:00";
      if (time[0] == dateData[1]) {
        end = time[1];
      }
      dateInfo[1] = dateData[1] + " " + end;
    }
    onScreenQuery(dateInfo, conditionValue, answer);
  };

  return (
    <ScreenContent>
      <div className="screen-head" onClick={() => setScreenShow(!screenShow)}>
        <PartitionOutlined /> 数据筛选
      </div>
      <div className="screen-box" style={{ display: screenShow ? "block" : "none" }}>
        <div className="screen-arrow">
          <i></i>
        </div>
        <div className="screen-label">题目筛选：</div>
        <div className="screen-subject">
          <div className="screen-condition">
            <Radio.Group buttonStyle="solid" value={conditionValue} onChange={e => setCondition(e.target.value)}>
              <Radio.Button value="and">且</Radio.Button>
              <Radio.Button value="or">或</Radio.Button>
            </Radio.Group>
            <Button onClick={addCondition}>添加条件</Button>
          </div>
          {screenData.map((item, index) => (
            <div className="screen-item flex align-items" key={item.id}>
              <Select
                placeholder="请选择"
                className="screen-select"
                showSearch
                value={item.value}
                fieldNames={{ label: "title", value: "id" }}
                options={screenQuestion}
                filterOption={(input, option) => (option?.title ?? "").toLowerCase().includes(input.toLowerCase())}
                onChange={vlaue => questionChange(index, Number(vlaue))}
              ></Select>
              {item.option.length !== 0 && (
                <Select
                  placeholder="请选择"
                  className="screen-select"
                  showSearch
                  mode="multiple"
                  maxTagCount="responsive"
                  value={item.answer}
                  fieldNames={{ label: "content", value: "id" }}
                  options={item.option}
                  filterOption={(input, option) => (option?.content ?? "").toLowerCase().includes(input.toLowerCase())}
                  onChange={value => setScreenData(screenData.map((item, i) => (i === index ? { ...item, answer: value } : item)))}
                ></Select>
              )}
              <Button type="primary" danger onClick={() => removeCondition(index)}>
                删除
              </Button>
            </div>
          ))}
        </div>
        <div className="screen-label">提交时间：</div>
        <div className="screen-item flex align-items">
          <div className="screen-content">
            <RangePicker value={date} onChange={value => setDate(value)} />
          </div>
        </div>
        <div className="screen-item flex align-items">
          <div className="screen-content">
            <Button style={{ marginRight: 20 }} onClick={() => reset()}>
              重置
            </Button>
            <Button type="primary" onClick={screenClick}>
              查询
            </Button>
          </div>
        </div>
      </div>
    </ScreenContent>
  );
}
export default observer(Screen);
